#include "xtypes.h"
#include "xtinystack.h"

#include <stdlib.h>
#include <string.h>




xResult xStack_Clear( pstack_t _Stack )
{
	if(_Stack==NULL)
		return XR_FAIL;

	_Stack->top = -1;
	return XR_OK;
}

xResult xStack_Push( pstack_t _Stack, int_t _Val )
{
	if(_Stack==NULL)
		return XR_FAIL;

	if( _Stack->top < _Stack->size )
	{
		_Stack->buf[++_Stack->top] = _Val;
		return XR_OK;
	}
	else
	{
		return XR_FAIL;
	}
}

xResult xStack_Pop( pstack_t _Stack )
{
	if(_Stack==NULL)
		return XR_FAIL;

	if( _Stack->top >= 0 )
	{
		_Stack->top--;
		return XR_OK;
	}
	else
	{
		return XR_FAIL;
	}
}

int_t xStack_GetTop( pstack_t _Stack )
{
	if(_Stack==NULL)
		return INVALID_VALUE;

	if( _Stack->top<0 )
		return INVALID_VALUE;
	else
		return _Stack->buf[_Stack->top];
}

bool_t xStack_IsEmpty( pstack_t _Stack )
{
	if(_Stack==NULL)
		return TRUE;

	if( _Stack->top<0 )
		return TRUE;
	else
		return FALSE;
}

pstack_t xStack_Create( int_t _Size )
{
	pstack_t _Stack=NULL;
	if( _Size <=0)
		return NULL;

	_Stack = (pstack_t)malloc(sizeof(stack_t));
	if(_Stack==NULL)
		return NULL;

	int_t *pBuf = (int_t *)malloc(sizeof(int_t)*_Size);
	if(pBuf==NULL)
	{
		free(_Stack);
		return NULL;
	}

	_Stack->buf = pBuf;
	_Stack->unused = 0;
	_Stack->size = _Size;	
	_Stack->top = -1;

	return _Stack;
}

xResult xStack_Release( pstack_t _Stack )
{
	if(_Stack==NULL)
		return XR_FAIL;

	if(_Stack->buf==NULL)
		return XR_FAIL;

	free(_Stack->buf);
	free(_Stack);

	return XR_OK;
}



xResult xStack_Resize(  pstack_t _Stack, int_t _NewSize )
{
	if(_Stack==NULL)
		return XR_FAIL;

	if( _NewSize <= _Stack->top+1 )
		return XR_FAIL;

	int_t *pBuf = (int_t *)malloc(sizeof(int_t)*_NewSize);
	if(pBuf==NULL)
		return XR_FAIL;

	memcpy( pBuf, _Stack->buf, _Stack->top+1 );

	free(_Stack->buf);
	_Stack->buf = pBuf;
	_Stack->size = _NewSize;
	_Stack->top = -1;

	return XR_OK;
}
